﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.Entities;
using MovieRental.EfRepositoryLibrary.Mappers;
using MovieRental.DataInterfaces;
using MovieRental.GeneralDataExceptions;

namespace MovieRental.EfRepositoryLibrary
{
    public class EfLoanCartRepository : EfRepository<LoanCartInfo, Guid, LoanCart, LoanCart>, ILoanCartRepository
    {
        public EfLoanCartRepository(string connectionString)
            : base(connectionString)
        {
            _mapper = new LoanCartMapper();
        }

        public override void Save(LoanCartInfo entity)
        {
            using (var context = CreateContext())
            {
                var loansToDelete = context.Loans.AsEnumerable().Where(x => x.LoanCartId == entity.Id && !entity.Loans.Any(y => y.Id == x.Id));
                foreach (var loan in loansToDelete)
                    context.Loans.DeleteObject(loan);

                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Connection error.", ex);
                }
            }
            base.Save(entity);
        }

        public IEnumerable<LoanCartInfo> LoadAllForDay(DateTime date)
        {
            using (var context = CreateContext())
            {
                try
                {
                    return context.LoanCarts.AsEnumerable().Where(x => x.LoanDate.Date == date.Date).Select(x => _mapper.ConvertBack(x)).ToList();
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Can't load objects from the db.", ex);
                }
            }
        }

        public IEnumerable<LoanCartInfo> LoadAllForCustomer(Guid customerId)
        {
            using (var context = CreateContext())
            {
                try
                {
                    return context.LoanCarts.AsEnumerable().Where(x => x.CustomerId == customerId).Select(x => _mapper.ConvertBack(x)).ToList();
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Can't load objects from the db.", ex);
                }
            }
        }
    }
}
